﻿using Nop.Core.Infrastructure;
using Nop.Services.Logging;
using Nop.Services.Tasks;
using System;

namespace Nop.Services.WindAlert
{
    /// <summary>
    /// Represents a task for sending queued message 
    /// </summary>
    public partial class UpdateWaveSpotsTask : ITask
    {

        /// <summary>
        /// Executes a task
        /// </summary>
        public void Execute()
        {
            var spotService = EngineContext.Current.Resolve<ISpotService>();
            var waveDataService = EngineContext.Current.Resolve<IWaveDataService>();

            var spots = spotService.GetAllSpots(isWave:true);
            
            foreach (var spot in spots)
            {
                if (!string.IsNullOrEmpty(spot.WaveDataUrl))
                {
                    try
                    {
                        var spotData = waveDataService.UpdateWaveSpot(spot);
                        if (spotData != null)
                        {
                            var lastWave = waveDataService.GetWaveDataBySpotIdTop1(spot.Id);
                            if (lastWave == null)
                                waveDataService.InsertWaveData(spotData);
                            else if (lastWave.WaveTimeUTC != spotData.WaveTimeUTC)
                                waveDataService.InsertWaveData(spotData);
                        }

                    }
                    catch (Exception exc)
                    {
                        var logger = EngineContext.Current.Resolve<ILogger>();
                        logger.Error(string.Format("Error updateing spots. {0}", exc.Message), exc);
                        continue;
                    }
                }
            }
        }
    }
}
